package config;

import java.io.IOException;
import java.util.Properties;

import util.common.AbstractManager;

/**
 * Class manages global engine properties.
 * 
 * @author Joel Rausch
 */
public class ConfigManager extends AbstractManager {

	/** Global properties */
	private final Properties properties = new Properties();
	
	@Override
	public void startup() throws Exception {
		
		// Load configuration file
		parent.files.addSearchPath(new String[] {"bin"});
		try {
			properties.load(parent.files.textReader("config.ini"));
		} catch(IOException e) {
			// No configuration file, we use default properties
		}
	}

	@Override
	public void shutdown() throws Exception {
		save();
	}

	/**
	 * Returns the value of the named property, or null if it
	 * does not exist.
	 * @param name
	 * @return
	 */
	public String getProperty(String name) {
		return properties.getProperty(name);
	}
	
	/**
	 * Return the value of the named property if it exists, or create
	 * a new property containing the default value if it does not.
	 * @param name Name of property
	 * @param defaultValue Default value of property
	 * @return Value of property
	 */
	public String getProperty(String name, String defaultValue) {
		if(properties.contains(name)) {
			return properties.getProperty(name);
		} else {
			properties.setProperty(name, defaultValue);
			return defaultValue;
		}
	}
	
	/**
	 * Return the integer value of the named property if it exists, or create
	 * a new property containing the default integer value if it does not.
	 * @param name Name of property
	 * @param defaultValue Default value of property
	 * @return Value of property
	 */
	public int getIntProperty(String name, int defaultValue) {
		String value = getProperty(name, Integer.toString(defaultValue));
		try {
			return Integer.parseInt(value, 10);
		} catch(NumberFormatException e) {
			//TODO Log number format error
			return 0;
		}
	}
	
	/**
	 * Immediately save current set of properties.
	 * @throws IOException 
	 */
	public void save() throws IOException {
		// Writer which opens as overwrite / create (we really want the file ;)
		properties.store(parent.files.textWriter(
				new String[] {"bin", "config.ini"}), "Lunecy Engine Config");
	}
}
